import React, {Component} from "react";
import {Button, Icon, Table} from "antd";
import './style.css'
import Text from "antd/es/typography/Text";
import {inject, observer} from "mobx-react";

export default @inject('store') @observer
class MachineStatus extends Component {
    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id'
        },
        {
            title: 'IP',
            dataIndex: 'ip',
            key: 'ip'
        },
        {
            title: 'CPU',
            dataIndex: 'cpu',
            key: 'cpu',
            render: (text) => (<Text>{text}%</Text>)
        },
        {
            title: '内存',
            render: (item) => (<Text>{Math.round(item.memory * 1000 / item.total_memory) / 10}%</Text>)
        },
        {
            title: '已用内存',
            dataIndex: 'memory',
            key: 'memory',
            render: (text) => (<Text>{Math.round(text / 1048576)} MB</Text>)
        },
        {
            title: '总内存',
            dataIndex: 'total_memory',
            key: 'total_memory',
            render: (text) => (<Text>{Math.round(text / 1048576)} MB</Text>)
        },
    ];

    limit = 8;

    constructor(props) {
        super(props);

        this.state = {
            data: [],
            current: 1,
            machineCount: 0,

            stopVisible: false,
            stopItem: null,
        }
    }

    componentDidMount() {
        this.getPage(0);
    }


    _changeCurrent(page) {
        this.setState({current: page});
        this.getPage(this.limit * (page - 1));
    }

    getPage(offset) {
        window.$http.postForm("/machine/gets", {
            offset: offset,
            limit: this.limit,
        }).then(res => {
            if (res.status === 10000) {
                this.setState({data: res.machines, machineCount: res.count});
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        })
    }

    render() {
        return (
            <div>
                <Button type={"primary"} style={{marginLeft: 10, marginBottom: 10}}
                        onClick={() => this.getPage(this.limit * (this.state.current - 1))}>
                    <Icon type={'redo'}/>刷新</Button>
                <Table rowKey={record => record.id}
                       style={{width: '100%'}}
                       pagination={{
                           total: this.state.machineCount,
                           onChange: (page) => this._changeCurrent(page),
                           pageSize: this.limit,
                           current: this.state.current,
                       }}
                       columns={this.columns} dataSource={this.state.data}/>
            </div>
        )
    }
}